//自定义公众方法

window.apiUrl = "http://feiyutiyu.cn";//接口路由  http://feiyu.test.jiaoxin-tech.cn
window.thisUrl = "http://feiyutiyu.cn";//本站路由
var isAndroid = (/android/gi).test(navigator.appVersion),
    isIDevice = (/iphone|ipad/gi).test(navigator.appVersion);
//alert(feiyu.getToken());
var isMastlogin = false;

var devicesuccess = true;
var waitfun = [];
$.share = function () {
    if (isWeiXin()) {
        wx.share("飞羽体育", "飞羽体育是一款关于订场app，主要目标人群是运动爱好者。功能包括GPS精准定位附近运动休闲娱乐场馆，为您提供方便、快捷的运动方式及参考，让你感受运动的快乐。", location.href, thisUrl + '/Wap/images/vult17.png');
    } else if (isFeiyu()) {
       /*
       * title：分享标题
       * link：分享链接
       * imgUrl：分享图标
       * desc：分享描述
       * */
        var data = feiyu.share(JSON.stringify({
            title: '飞羽体育',
            link: location.href,
            imgUrl: thisUrl + '/Wap/images/vult17.png',
            desc: "飞羽体育是一款关于订场app，主要目标人群是运动爱好者。功能包括GPS精准定位附近运动休闲娱乐场馆，为您提供方便、快捷的运动方式及参考，让你感受运动的快乐。"
        }));
        data.nethod = "share";
        pushdata(data);
    } else {
        alert("在微信或app中打开才能分享");
    }
}
$.login = function (cb) {
    if (isWeiXin()) {//微信浏览器
        $.weixinLogin();
    } else if (isFeiyu()) {//客户端内
        //waitfun.push(cb);
		let params = JSON.parse(window.feiyu.deviceLogin());
		
        if (devicesuccess) {
            //alert("2");
            devicesuccess = false;
            $.ajax({
				url: apiUrl+ '/Api/Login/Device1',
				data: params,
				type:"POST",
				success:function(result){
					if (result.errcode == 0){
						localStorage.setItem("token", result.data.token);
						location.replace(location.href);
						return;
					}
					location.href =window.thisUrl+'/wap/index.html#/login?backurl=' + encodeURIComponent(location.href);
				}
			});
        }
        //TODO 客户端内未登录情况
    } else {//其他环境
        //waitfun.push(cb);
        //console.log(waitfun);
        //if (devicesuccess) {
        //    devicesuccess = false;
        //    if (true) {
        //        //for (var fun in waitfun) {
        //        //    console.log(fun);
        //        //    $.ajax(fun);
        //        //}
        //        $(waitfun).each(function (index) {
        //            $.ajax(waitfun[index]);
        //        })
        //        waitfun = [];
        //        devicesuccess = true;
        //    }
        //}
        //return false;
        console.log("在其他浏览器打开，调用h5登录");
        $.h5login();
        //window.token = "427394a6e6c1441bafb27aff382ec1a7";
    }
},
$.weixinLogin = function () {
    $.ajax({
        url: thisUrl + "/Api/Weixin/OAuth",
        type: "POST",
        data: { backurl: location.href },
        success: function (data) {
            if (data.errcode == 0) {
                location.href = data.href;
            }
        },
        error: function () {
            alert("服务器响应失败");
        }
    })
},
$.h5login = function () {
    console.log("调用h5登录");
    location.href = window.thisUrl + '/wap/index.html#/login?backurl=' + encodeURIComponent(location.href);
}
//console.log(window.token);
//转意符换成普通字符
$.escape2Html = function (str) {
    var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
}
//获取url中的参数
$.getParam = function (name) {
    var url = window.location.search;
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var result = url.substr(1).match(reg);
    return result ? decodeURIComponent(result[2]) : null;
}
//将字符串对象转换为对象
var evalTo = function (data) {
    return eval('(' + data + ')');
}
//判断是否在微信浏览器内
function isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

//if (isWeiXin()) {
//    $('header').attr('style', 'display:none');
//}

if (isFeiyu()) {
    $('.bottomdiv').attr('style', 'display:none');
}
function isFeiyu() {
	return window.feiyu;
}


if (!isFeiyu()) {
    window.token = localStorage.getItem("token");
    //alert(window.token)
    //alert(window.token);
    //if (localStorage.getItem("token") == "null" || localStorage.getItem("token") == null) {
    //    $.login();
    //}
    //window.token = "5e37cde8586b4a2eb1646002bacfecd1";
}
else {
    //alert(feiyu.getToken())
    try {
        window.token = feiyu.getToken();
    }
    catch (ex) {
        //alert(typeof (feiyu));
        alert(ex.message);
    }
}
if (isMastlogin && (window.token == "null" || window.token == null)) {
    $.login();
}
(function ($) {
    var ajax = $.ajax;
    $.ajax = function (requestobj) {
        var error = requestobj.error;
        var success = requestobj.success;
        requestobj.data = Object.assign({ "token": window.token }, requestobj.data);
        if (requestobj.url.indexOf(apiUrl) < 0) {
            ajax(requestobj);
            return;
        }
        requestobj.success = function (data, textStatus, xhr) {
            console.log(data);
            if (data.errcode == -2)
                $.login(requestobj);
            else
                success(data);
        };
        requestobj.error = function (xhr, status, err) {
            if (requestobj.error == null)
                error(xhr, status, err);
            else
                alert("服务器响应异常");
        };
        ajax(requestobj);
    }
})(jQuery);

$.alerts = {
    alert: function (message, callback) {
        //if (title == null) title = 'Alert';
        $.alerts._show(message, null, 'alert', function (result) {
            if (callback) callback(result);
        });
    },
    confirm: function (message, callback) {
        var callbackob = callback;
        console.log(callbackob)
        //if (title == null) title = 'Confirm';
        $.alerts._show(message, null, 'confirm', function (result) {
            //console.log(callbackob)
            if (callback)
                callback(result);
        });
    },
    _show: function (msg, value, type, callback) {
        if (type == "alert") {
            var div1 = document.createElement("div");
            var div2 = document.createElement("div");
            var div3 = document.createElement("div");
            var div4 = document.createElement("div");
            var div5 = document.createElement("div");
            var div6 = document.createElement("div");
            var span = document.createElement("span");
            div1.className = "am-modal am-modal-alert am-modal-active alertsuoyou";
            div1.style = "display: block";
            div2.className = "am-modal-dialog";
            div3.className = "am-modal-hd";
            div4.className = "am-modal-bd";
            div5.className = "am-modal-footer";
            div6.className = "am-dimmer am-active alerthei";
            div6.style = "display: block";
            span.className = "am-modal-btn alertqueding";

            div3.innerHTML = "温馨提示！";
            div4.innerHTML = msg ? msg : "";
            span.innerHTML = "确定";

            div1.appendChild(div2);
            div2.appendChild(div3);
            div2.appendChild(div4);
            div5.appendChild(span);
            div2.appendChild(div5);
            div = div1;
            document.getElementsByTagName("body")[0].appendChild(div);
            document.getElementsByTagName("body")[0].appendChild(div6);
        }
        if (type == "confirm") {
            var div1 = document.createElement("div");
            var div2 = document.createElement("div");
            var div3 = document.createElement("div");
            var div4 = document.createElement("div");
            var div5 = document.createElement("div");
            var div6 = document.createElement("div");
            var span = document.createElement("span");
            var span2 = document.createElement("span");
            div1.className = "am-modal am-modal-confirm am-modal-active alertsuoyou";
            div1.style = "display: block";
            div2.className = "am-modal-dialog";
            div3.className = "am-modal-hd";
            div4.className = "am-modal-bd";
            div5.className = "am-modal-footer";
            div6.className = "am-dimmer am-active alerthei";
            div6.style = "display: block";
            span.className = "am-modal-btn alertqueding";
            span2.className = "am-modal-btn alertquxiao";

            div3.innerHTML = "温馨提示！";
            div4.innerHTML = msg ? msg : "";
            span.innerHTML = "确定";
            span2.innerHTML = "取消";

            div1.appendChild(div2);
            div2.appendChild(div3);
            div2.appendChild(div4);
            div5.appendChild(span2);
            div5.appendChild(span);
            div2.appendChild(div5);
            div = div1;
            document.getElementsByTagName("body")[0].appendChild(div);
            document.getElementsByTagName("body")[0].appendChild(div6);
        }
        //_html += '</div></div>';

        //必须先将_html添加到body，再设置Css样式  
        //$("body").append(_html);

        //GenerateCss();

        switch (type) {
            case 'alert':

                $(".alertqueding").click(function () {
                    $.alerts._hide();
                    callback(true);
                });
                $(".alertqueding").focus().keypress(function (e) {
                    if (e.keyCode == 13 || e.keyCode == 27) $(".alertqueding").trigger('click');
                });
                break;
            case 'confirm':

                $(".alertqueding").click(function () {
                    $.alerts._hide();
                    if (callback) callback(true);
                });
                $(".alertquxiao").click(function () {
                    $.alerts._hide();
                    if (callback) callback(false);
                });
                $(".alertquxiao").focus();
                $(".alertqueding, .alertquxiao").keypress(function (e) {
                    if (e.keyCode == 13) $(".alertqueding").trigger('click');
                    if (e.keyCode == 27) $(".alertquxiao").trigger('click');
                });
                break;


        }
    },
    _hide: function () {
        $(".alertsuoyou").remove();
        $(".alerthei").remove();
    }
}
// Shortuct functions  
window.alert = function (message, callback) {
    $.alerts.alert(message, callback);
}

window.confirm = function (message, callback) {
    $.alerts.confirm(message, callback);
};
//    confirm('系统确认框', '你确认提交该条数据吗', function (r) {
//        if (r) {
//            alert("123");
//        }
//    });

//util.pay({
//    number: "1234124",
//    type: 1,
//    success: function (res) { },
//    error: function (res) {
//        if (res.errcode == 0) {
//            alert("支付成功");
//            location.replace(location.href);
//        }
//        else {
//            alert("zhifushibai");
//        }
//    }
//})


//sdk.pay(1, "21", function () {
//}, function () {
//})

//function pay(type, orderid, success, error) {
//    var data = feiyu.pay(type, orderid);
//    if (data.errode == 0) {
//        success();
//    }
//    else
//        error()
//}


    function feiyucallback(backcode)
    {
        alert(backcode);
        if(backcode==0)//成功
        {
            alert("成功");
        }
        else if(backcode==-1)//失败
        {
            alert("失败");
        }
        else if (backcode == -2)//取消
        {
            alert("取消");
        }
    }

$.wxpay = function (payobj) {
    if (isFeiyu()) {
        /*
        * orderId：订单id
        * orderType：订单类型
        * payType：支付类型
        * */
        $.ajax({
            type: 'POST',
            url: apiUrl + '/Api/Weixin/TyPay',
            data:{
                Id: payobj.Id,
                type: payobj.type,
                PayType: 3
            },
            success: function (result) {
                if(result.errcode < 0){
                    showTips(result.errmsg);
                    return;
                }
                var data = {
                    orderId: payobj.Id,
                    orderType: payobj.type,
                    payType: 3,
                    payData: result.data
                };
                window.feiyu.pay(JSON.stringify(data));
            }
        });

    } else if (isWeiXin()) {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            $.ajax({
                url: apiUrl + "/Api/Weixin/TyPay",
                data: { Id: payobj.Id, type: payobj.type, PayType: 1 },
                type: "POST",
                success: function (data) {
                    if (data.errcode == 0) {
                        WeixinJSBridge.invoke(
                          'getBrandWCPayRequest',
                          data.data,
                          function (res) {
                              if (res.err_msg == "get_brand_wcpay_request:ok") {
                                  payobj.success({ errcode: 0, errmsg: "支付成功" });
                              }
                          }
                        );
                    } else {
                        payobj.error({ errcode: -1, errmsg: data.errmsg });
                        //alert(data.errmsg);
                    }

                }
            });
        }
    }
    else {
        $.ajax({
            url: apiUrl + "/Api/Weixin/TyPay",
            data: { Id: payobj.Id, type: payobj.type, PayType: 2 },
            type: "POST",
            success: function (data) {
                if (data.errcode == 0) {
                    //console.log(data.data)
                    location.replace(data.data.mweb_url);
                } else {
                    payobj.error({ errcode: -1, errmsg: data.errmsg });
                    //alert(data.errmsg);
                }

            }
        });
        //payobj.error({ errcode: -1, errmsg: "请在微信客户端内支付" });
    }
}


/** 
* 返回前一页（或关闭本页面） 
* <li>如果没有前一页历史，则直接关闭当前页面</li> 
*/
function goBack() {
    if (isFeiyu()) {
        window.history.back();
    }
    else {
        if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) { // IE 
            if (history.length > 0) {
                window.history.go(-1);
            } else {
                window.opener = null;
                window.close();
            }
        } else { //非IE浏览器 
            if (navigator.userAgent.indexOf('Firefox') >= 0 ||
            navigator.userAgent.indexOf('Opera') >= 0 ||
            navigator.userAgent.indexOf('Safari') >= 0 ||
            navigator.userAgent.indexOf('Chrome') >= 0 ||
            navigator.userAgent.indexOf('WebKit') >= 0) {

                if (window.history.length > 1) {
                    window.history.go(-1);
                } else {
                    window.opener = null; window.close();
                }
            } else { //未知的浏览器 
                window.history.go(-1);
            }
        }
    }
}

/*
* 展示提示信息
* tips: 提示信息
* */
var showTips = function(tips){
    tips = tips || '提示信息';
    if(document.getElementById('SucTips')) return;
    var div = document.createElement('div');
    div.id = 'SucTips';
    div.innerHTML = '<span>' + tips + '</span>';
    document.body.appendChild(div);
    var timer = setTimeout(function(){
        document.getElementById('SucTips').parentNode.removeChild(document.getElementById('SucTips'));
        clearTimeout(timer);
    } , 4000)
};

/*
* 支付回调
* obj{
*  orderId: 订单id
*  errCode: 支付状态(0成功 , -1错误 , -2用户取消)
*  errStr：errCode为-1时才有值
* }
* */
window.payCallBack = function(obj){
    var o = JSON.parse(obj);
    if(o.errCode == -2){
        showTips('取消支付');
        return;
    }
    if(o.errCode == -1){
        showTips(o.errStr || '支付失败!');
        return;
    }
    window.replace(location.href);
};
